package com.lijian.service;

import com.alibaba.fastjson.JSON;
import com.lijian.model.BaseStationCoordinate;
import com.lijian.model.CoordinateData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * WebSocket服务
 *
 * @author 李健
 * @date 2021/03/01
 */
@Slf4j
@Service
@ServerEndpoint("/location")
public class WebSocket {

    private static Session session;

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocket.applicationContext = applicationContext;
    }

    @OnOpen
    public void onOpen(Session s) {
        session = s;
        BaseStationCoordinate baseStationCoordinate = applicationContext.getBean(BaseStationCoordinate.class);
        new SerialPortConnect().listenData(baseStationCoordinate, this);
    }

    public void sendMessage(CoordinateData data) throws Exception {
        String jsonData = JSON.toJSONString(data);
        if(session == null){
            log.error("未连接，发送失败");
            return;
        }
        session.getBasicRemote().sendText(jsonData);
    }

}
